package com.dingwen.sprboojwtstu.controller;

import com.dingwen.sprboojwtstu.util.JwtUtil;
import com.dingwen.sprboojwtstu.entity.UserEntity;
import com.dingwen.sprboojwtstu.result.Result;
import com.dingwen.sprboojwtstu.result.ResultGenerator;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * login controller
 *
 * @author dingwen
 * 2021.05.31 11:26
 */
@Api(tags = "登录")
@RestController
public class LoginController {

    /**
     * 登录
     *
     * @param userEntity 用户实体
     * @return {@link Result}
     */
    @ApiOperation("登录")
    @ApiImplicitParam(value = "用户实体", required = true, type = "UserEntity")
    @PostMapping("/login")
    public Result login(@RequestBody UserEntity userEntity) {
        // 模拟登录失败
        if (userEntity.getUsername().equalsIgnoreCase("failure")) {
            return ResultGenerator.genFailureResult("登录失败").setCode(401);
        }
        // 模拟登录成功
        // 生成jwt token
        //构建payload
        Map<String, Object> payload = new HashMap<>();
        payload.put("username", userEntity.getUsername());
        payload.put("permissionList", userEntity.getPermissionList());

        // 生成jwt token
        String token = JwtUtil.createJwtToken(payload);

        return ResultGenerator.genOkResult(token).setMessage("登录成功");
    }
}